import { $userGetSmsCode, $userLoginBySmsCode } from "api";
import React, { useRef, useState } from "react";
import "./index.less";
import classNames from "classnames";
import {useHistory} from 'react-router';
import {updateToken,updatePhone} from 'redux/index';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

function Login(props) {
  let ref1 = useRef(null);
  let ref2 = useRef(null);
  let history = useHistory();

  // 定义状态
  let [phone, setPhone] = useState("");
  let [smsCode, setSmsCode] = useState("");

  // 获取验证码
  let getCode = () => {
    // 判断电话号码是否符合规则
    // ...
    $userGetSmsCode({ phone }).then((res) => { 
      setSmsCode(res.result.smsCode);
    });
  };

  let login = () => {
    $userLoginBySmsCode({ phone, smsCode }).then((res) => { 
      props.updateToken(res.result.token);
      props.updatePhone(res.result.phone);
      history.push('/my');
    });
  };

  return (
    <div className="login-index">
      <div onClick={()=>{ref1.current.focus()}}
      className="inp-box">
        <input ref={ref1} 
          onChange={(event) => {
            setPhone(event.target.value);
          }}
          name="phone"
          className="inp f16"
          placeholder="请输入手机号码"
          maxLength="11"
          value={phone}
        />
      </div>
      <div onClick={()=>{ref2.current.focus()}}
      className="inp-box flex jc-sb aic">
        <input ref={ref2}
          onChange={(event) => {
            setSmsCode(event.target.value);
          }}
          name="smsCode"
          className="inp f16"
          placeholder="请输入验证码"
          value={smsCode}
        />
        <a onClick={getCode} className="am-button code am-button-small fcc">
          <span>获取验证码</span>
        </a>
      </div>
      <div className="flex jc-c mt-20">
        <a className="am-button ml-10 am-button-small fcc">
          <span>取 消</span>
        </a>
        <a
          onClick={login}
          className={classNames("am-button ml-10 am-button-small fcc", {
            enabled: !!smsCode,
          })}
        >
          <span>登 录</span>
        </a>
      </div>
    </div>
  );
}

// export default Login;

function mapStateToProps(state) {
  return {
    token: state.token
  }
}

function mapDisPatchToProps(dispatch) {
  return {
    updateToken: bindActionCreators(updateToken,dispatch),
    updatePhone: bindActionCreators(updatePhone,dispatch),
  } 
}

export default connect(mapStateToProps,mapDisPatchToProps)(Login);